package top.cardone.context.func;

import org.apache.commons.collections.MapUtils;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import top.cardone.core.util.func.Func2;

import java.util.Map;

/**
 * Created by cardone-home-001 on 2016/4/20.
 */
public class DefaultValueFunc implements Func2<Object, Map<String, Object>, Map<String, Object>> {
	@Override
	public Object func(Map<String, Object> map, Map<String, Object> params) {
		String key = MapUtils.getString(params, "key");

		if (StringUtils.isBlank(key)) {
			return MapUtils.getObject(params, "defaultValue");
		}

		Object val = MapUtils.getObject(map, key);

		if (val instanceof String) {
			if (StringUtils.isNotBlank((String) val)) {
				return val;
			}

			return MapUtils.getObject(params, "defaultValue");
		}

		Object value = ObjectUtils.defaultIfNull(val, MapUtils.getObject(params, "defaultValue"));

		map.put(key, value);

		return value;
	}
}